package com.xjrsoft.module.base.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.core.tool.utils.DigestUtil;
import com.xjrsoft.module.base.entity.UserApiKey;
import com.xjrsoft.module.base.mapper.UserApiKeyMapper;
import com.xjrsoft.module.base.service.UserApiKeyService;
import com.xjrsoft.module.base.utils.ApiKey;
import lombok.extern.slf4j.Slf4j;
import org.flowable.idm.api.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Instant;

/**
 * @author by lisen
 * @Version 1.0.0
 * @Date 2024-05-31 16:11
 * @projectName: xjrsoft_new
 * @package: com.xjrsoft.module.base.service.impl
 * @className: UserApiKeyserviceImpl
 */
@Slf4j
@Service
public class UserApiKeyserviceImpl extends ServiceImpl<UserApiKeyMapper, UserApiKey> implements UserApiKeyService {

    @Override
    @Transactional
    public String getNewApiKey(){
        String userId = StpUtil.getLoginId().toString();
        Wrapper wrapper = Wrappers.<UserApiKey>query().lambda().eq(UserApiKey::getUserId,userId).eq(UserApiKey::getStatus, 1);
        UserApiKey userApiKey = this.getBaseMapper().selectOne(wrapper);
        UserApiKey newApiKey = new UserApiKey();
        String apiKey = ApiKey.uniqueId(32);
        String encrypt = DigestUtil.encrypt(apiKey);
        //log.info("注册："+apiKey+"加密后："+encrypt);
        newApiKey.setApiKey(encrypt);
        newApiKey.setUserId(userId);
        newApiKey.setCreateDate(Instant.now());
        if(userApiKey!=null){
            userApiKey.setStatus(0);
            this.updateById(userApiKey);
        }
        this.save(newApiKey);
        return apiKey;
    }

    @Override
    public boolean check(String apiKey){
        if(apiKey==null){
            return false;
        }
        String encrypt = DigestUtil.encrypt(apiKey);
        //log.info("对比："+apiKey+"加密后："+encrypt);
        Wrapper wrapper = Wrappers.<UserApiKey>query().lambda().eq(UserApiKey::getApiKey,encrypt).eq(UserApiKey::getStatus, 1);
        UserApiKey userApiKey = this.getBaseMapper().selectOne(wrapper);
        return userApiKey != null;
    }
}
